package com.gtenacg.fileservice.service.impl;

import com.gtenacg.fileservice.compent.BlackListProperties;
import com.gtenacg.fileservice.service.DownloadService;
import com.gtenacg.fileservice.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

@Slf4j
@Service
public class DownloadServiceImpl implements DownloadService {
    @Value("${file-path}")
    String basePath;

    final List<String> blacklist;
    final FileUtil fileUtil;

    public DownloadServiceImpl(BlackListProperties blacklist, FileUtil fileUtil) {
        this.blacklist = blacklist.getFileName();
        this.fileUtil = fileUtil;
    }


    @Override
    public byte[] getFileByte(String fileName) {
        byte[] data = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basePath + fileName));
            data = bis.readAllBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    @Override
    public InputStream getFileInputStream(String fileName) {
        InputStream is = null;
        try {
            File file = new File(basePath + fileName);
            if (file.isDirectory()) {
                File fileZip = new File(file.getPath() + "-zip.zip");
                if (!fileZip.exists()) {
                    log.info("文件夹zip包不存在，首次压缩 -> {}", fileName);
                    fileUtil.toZip(file);
                }
                file = fileZip;
            }
            is = new FileInputStream(file);

        } catch (FileNotFoundException e) {
            log.warn("文件不存在 -> {}", fileName);
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return is;
    }

    @Override
    public List<String> getFileList(String filePath, Predicate<File> predicate) {
        File file = new File(basePath + filePath);

        if (file.isFile()) return null;

        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            log.warn("文件列表为空，或者文件夹不存在 -> {}", filePath);
            return new ArrayList<>();
        }

        ArrayList<String> list = new ArrayList<>();
        for (File f : files) {
            if (blacklist.contains(f.getName().split("\\.")[0])) continue;

            if (predicate.test(f)) list.add(f.getName());
        }

        return list;
    }
}
